<template>
  <div id="conversation-message" v-if="message"
       class="conversation-message">
    <template v-if="!isRevoked">
      <!--  消息时间 -->
      <div :class="[isOwn?'time-right':'time-left']" class="time">{{messageTime}}</div>
      <!-- 消息信息  -->
      <div :class="[isOwn?'message-right':'message-left']" class="message">
        <!-- 消息发送者头像 -->
        <el-avatar class="avatar" :src="fromUserAvatar"></el-avatar>
        <!-- 聊天气泡 -->
        <div :class="[isOwn?'content-right':'content-left']"
             @contextmenu.prevent.stop="rightClick" class="content">
          <!-- 进度条 -->
          <el-progress v-if="showProgressBar && !isTextMessage"
                       :percentage="percentage"/>
          <!-- 图片消息 -->
          <template v-if="isImageMessage">
            <el-image fit="contain" :preview-src-list="imageList"
                      :src="messageContent"/>
          </template>
          <!-- 文本消息 -->
          <template v-if="isTextMessage">
            <pre>{{messageContent}}</pre>
          </template>
          <!-- 视频消息 -->
          <template v-if="isVideoMessage">
            <video controls
                   :src="messageContent">
            </video>
          </template>

          <!-- 文件消息 -->
          <template v-if="isFileMessage">
            <el-tooltip :open-delay="500"
                        effect="dark"
                        placement="top"
                        :content="fullFileName">
              <div @click="downloadFile" class="file">
                <i class="el-icon-document"/>
                <div class="info">
                  <span class="name">{{fileName}}</span>
                  <span class="size">{{fileSize}}</span>
                </div>
              </div>
            </el-tooltip>
          </template>
          <!-- 三角 -->
          <div :class="[isOwn?'angle-right':'angle-left']" class="angle "/>

          <!-- 消息撤回 -->
          <div @click="revocation"
               v-if="isOwn && isShowRevocation"
               class="revocation">
            <div/>
            撤回
          </div>
        </div>
        <!-- 消息的状态 -->
        <div v-if="isOwn" class="status">
          <svg-icon v-if="isRead" class="icon" icon-class="read"/>
          <svg-icon v-else class="icon" icon-class="unread"/>
        </div>
      </div>
    </template>
    <template v-else>
      <span class="revoked-message">
        {{isOwn?'你':'对方'}}撤回了一条消息
        <span v-if="!exceedTowMin && isTextMessage && isOwn"
              class="reedit"
              @click="reeditMessage">重新编辑</span>
      </span>
    </template>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import {getFullDate} from "@/utils/date";
  import tim from "@/tim";
  import TIM from 'tim-js-sdk'

  export default {
    name: "ConversationMessage",
    props: {
      message:{
        type:Object,
        default(){
          return {}
        }
      },
      imageList:{
        type:Array,
        default(){
          return []
        }
      }
    },
    computed:{
      ...mapGetters([
        'id','avatar','friendList',
      ]),
      showProgressBar(){
        return this.message.status === 'unSend'
      },
      percentage(){
        return Math.floor((this.message.progress || 0) * 100);
      },
      // 消息是否为当前用户发送
      isOwn(){
        return this.message.from === this.id
      },
      // 获取当前消息的发送者的头像
      fromUserAvatar(){
        if(this.isOwn){
          return  this.avatar
        }else {
          let user =  this.friendList.filter(item => item.userid === this.message.from)[0];
          if(user){
            return user.avatar
          }
          return ''
        }
      },
      // 当前消息发送时间
      messageTime(){
        const date = new Date(this.message.time * 1000)
        return getFullDate(date)
      },
      // 是否为文本消息
      isTextMessage(){
        return this.message.type === TIM.TYPES.MSG_TEXT
      },
      // 是否为图片消息
      isImageMessage(){
        return this.message.type === TIM.TYPES.MSG_IMAGE
      },
      // 是否为视频消息
      isVideoMessage(){
        return this.message.type === TIM.TYPES.MSG_VIDEO
      },
      // 是否为文件消息
      isFileMessage(){
        return this.message.type === TIM.TYPES.MSG_FILE
      },
      // 消息是否撤回
      isRevoked(){
        return  this.message.isRevoked
      },
      // 消息距离当前时间是否超出2分钟
      exceedTowMin(){
        // 消息发送的时间
        let sendTime = new Date(this.message.time * 1000).getTime()
        // 当前时间
        let currentTime = new Date().getTime()
        return currentTime - sendTime > 120000
      },
      // 消息内容
      messageContent(){
        if(this.isTextMessage){
          return this.message.payload.text
        }else if(this.isVideoMessage){
          return this.message.payload.videoUrl
        }else if(this.isImageMessage){
          return  this.message.payload.imageInfoArray[0].url
        }
      },
      // 文件名称
      fileName(){
        if(this.isFileMessage){
          let name = this.message.payload.fileName
          if(name.length<17){
            return name
          }
          let suffix = name.substring(name.lastIndexOf('.'),name.length)
          let prefix = name.substring(0,name.lastIndexOf('.'))
          let namePrefix = prefix.substring(0,5);
          let nameSuffix = prefix.substring(prefix.length-5,prefix.length);
          return namePrefix + '...' + nameSuffix + suffix;
        }
        return ''
      },
      // 完整文件名称
      fullFileName(){
        return this.isFileMessage ? this.message.payload.fileName:''
      },
      // 文件大小
      fileSize(){
        if(this.isFileMessage){
          let size = Math.ceil(this.message.payload.fileSize / 1024)
          if(size>1024){
            size = Math.ceil(size / 1024)
            return size + 'MB'
          }else{
            return size+"KB"
          }
        }
        return ''
      },
      // 消息是否已读
      isRead(){
        return this.message.isPeerRead
      }
    },
    data(){
      return{
        isShowRevocation:false, // 撤回消息按钮是否可见
      }
    },
    // 生命周期钩子函数
    mounted(){
      //为 当前页面绑定一个点击事件，用来隐藏撤回按钮
      document.addEventListener('click',()=>{
        this.isShowRevocation=false
      })
    },
    methods:{
      // 右键点击消息事件，显示撤回消息按钮
      rightClick(){
        console.log("点击了右键")
        this.isShowRevocation = true
      },
      // 撤回消息按钮
      revocation(){
        console.log("点击了消息撤回按钮")
        if(this.exceedTowMin){
          this.$store.commit('chat/showMessage',{
            message:'消息发送已经超过两分钟了，不能进行撤回了！',
            type:'error'
          })
          return
        }
        tim.revokeMessage(this.message).then(()=>{
          console.log("消息撤回成功！")
          this.$store.dispatch('chat/getConversationListTIM')
          // 请求消息列表
          this.$store.dispatch('chat/getRequestMessageList')
        }).catch(err=>{
          this.$store.commit('chat/showMessage',{
            message:err.message,
            type:'error'
          })
        })
      },
      // 重新编辑消息
      reeditMessage(){
        console.log("点击了重新编辑撤回消息："+this.message.payload.text)
        this.$emit('reeditMessage',this.message.payload.text)
      },
      // 文件下载
      downloadFile(){
        if(window.fetch){
          fetch(this.message.payload.fileUrl)
            .then(res=>res.blob())
            .then(blob=>{
              const a = document.createElement('a')
              a.href = window.URL.createObjectURL(blob)
              a.download = this.fullFileName
              a.click() // 自动触发超链接的点击事件
            })
        }else{
          const a = document.createElement('a')
          a.href = this.message.payload.fileUrl
          a.target = '_blank'
          a.download = this.fullFileName
          a.click()
        }
      }
    }
  }
</script>

<style lang="scss" scoped>

  .conversation-message {
    padding: 10px 15px 18px;
    .time {
      display: flex;
      display: -webkit-flex;
      padding: 0 0 6px;
      font-size: 12px;
    }
    .time-left {
      flex-direction: row;
    }
    .time-right {
      flex-direction: row-reverse;
    }
    .message-right {
      flex-direction: row-reverse;
      .content-right {
        margin-right: 16px;
        background-color: #98e165;
        .angle-right {
          right: -20px;
          border: 8px solid transparent;
          border-left: 15px solid #98e165;
        }
      }
    }

    .message-left {
      flex-direction: row;

      .content-left {
        margin-left: 16px;
        background-color: #5cadff;
        .angle-left {
          left: -20px;
          border: 8px solid transparent;
          border-right: 15px solid #5cadff;
        }
      }
    }

    .message {
      display: flex;
      display: -webkit-flex; //兼容 Safari浏览器
      .avatar { //头像
        min-width: 45px;
        min-height: 45px;
      }

      .content { // 气泡
        position: relative;
        padding:4px 10px;
        min-width: 20px;
        height: 100%;
        min-height: 30px;
        text-align: left;
        word-break: break-all;
        word-wrap: break-word;white-space : normal;
        box-shadow: 0 5px 10px 0 rgba(0, 0, 0, 0.2);
         pre{
           margin: 0;
           line-height: 30px;
           font-family: 微软雅黑,serif;
           white-space:pre-wrap;
           white-space:-moz-pre-wrap;
           white-space:-pre-wrap;
           white-space:-o-pre-wrap;
           word-wrap:break-word;
         }
        .file{
          display: flex;
          width: 259px;
          height: 64px;
          padding: 0 26px;
          cursor:pointer;
          background-color: #ffffff;
          &:hover{
            background-color: #f2f3f5;
          }
          i{
            font-size: 40px;
            line-height: 64px;
          }
          .info {
            display: flex;
            flex-direction: column;
            margin: 0 12px;
            .name {
              margin: 12px 0 5px;
              font-size: 14px;
            }
            .size {
              color: #d9baa5;
              font-size: 12px;
            }
          }
        }
        .el-image, video {
          cursor: pointer;
          outline: none;
        }
        video{
          width: 300px;
        }
        .el-image{
          width: 280px;
        }
        .angle { // 三角
          position: absolute;
          top: 8px;
          width: 0;
          height: 0;
        }
        .revocation{
          position: absolute;
          left: -60px;
          top: 50%;
          margin-top: -25px;
          width: 45px;
          height: 30px;
          font-size: 13px;
          color: #FFFFFF;
          text-align: center;
          line-height: 30px;
          cursor: pointer;
          background-color: #303133;
          &:hover{
            div{
              border-left:10px solid  #5c5d61;
            }
            background-color: #5c5d61;
          }
          div{
            position: absolute;
            right: -15px;
            top: 9px;
            width: 0;
            height: 0;
            border: 5px solid transparent;
            border-left: 10px solid #303133;
          }
        }
      }
      .status { // 消息状态 已读/未读
        position: relative;
        min-width: 26px;
        color: #99799f;
        font-size: 12px;
        .icon {
          position: absolute;
          bottom: 5px;
          right: 8px;
          font-size: 15px;
        }
      }
    }
    .revoked-message{
      padding: 5px;
      font-size: 12px;
      color: #7e848c;
      background-color: #e4e7eb;
      .reedit{
        cursor:pointer;
        color: #006ce0;
      }
    }

  }
</style>
